package com.hxc.interceptor;

import cn.hutool.jwt.JWT;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if (!StringUtils.isEmpty(cookies)){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("login_token")){
                    byte[] key = "1234567890".getBytes();
                    String token = cookie.getValue();
                    // 默认验证HS265的算法
                    boolean b = JWT.of(token).setKey(key).verify();
                    if (b){
                        return true;
                    }
                }
            }
        }
        response.sendRedirect("/user/toLogin");
        return false;
    }
}
